<?php

function sopily_create_function(&$instance){

	$handle=opendir(dirname(__FILE__));
	while (false !== ($func = readdir($handle))) {
		
		if(strpos($func,'function.')===0){
			$func=str_replace(Array('function.','.php'),'',$func);
			$instance->_functions[$func]=
				create_function('$param=NULL','echo sopily_call_function((is_array($param))?$param:func_get_args(),"'.$func.'");');
		}
		else if(strpos($func,'modifier.')===0 ){
			$func=str_replace(Array('modifier.','.php'),'',$func);
			$instance->_functions[$func]=
				create_function('','$param=array_slice(func_get_args(),1);return sopily(func_get_arg(0),Array("'.$func.'"=>$param));'); 
		}
	}
	closedir($handle);
}


function sopily_call_function($param,$func){
	reset($param);
	if(is_int(key($param))){
		$new_param=Array();
		for($i=0;$i<count($param);$i+=2){
			$new_param[$param[$i]]=$param[$i+1];
		}
		$param=$new_param;
		unset($new_param);
	}

	global $sopily_instance;
	$smarty=&$sopily_instance;
	$dir=$sopily_instance->_plugin_dir;
	require_once($dir.'function.'.$func.'.php');

	//smarty_function_html_select_date($params, &$smarty)
	return call_user_func('smarty_function_'.$func,$param,$smarty);
}

function sopily($str,$param=NULL){

	if(empty($param))
		return $str;

	if(!is_array($param)){
		if(func_num_args()>2)
			$param=Array($param=>array_slice(func_get_args(),2));
		else
			$param=Array($param);
	}

	global $sopily_instance;
	$smarty=&$sopily_instance;
	$dir=$sopily_instance->_plugin_dir;
	foreach($param as $key=>$value){
		$func=(is_int($key))?$value:$key;

		if(!is_file($dir.'modifier.'.$func.'.php'))
			continue;
		require_once($dir.'modifier.'.$func.'.php');
		$func="smarty_modifier_".$func;

		if(is_array($value)){
			// ex default:"www.sopili.net"
			$str=call_user_func_array($func,array_merge(array($str),$value));

		}
		else{  //ex capitalize
			$str=call_user_func($func,$str);
		}
	}
	return $str;


}


function sopily_popup_init($src){
	echo '<script src="'.$src.'" type="text/javascript"></script>';
}

function sopily_config_load($src){
	global $sopily_instance,$sopily_config;

	include( $sopily_instance->config_dir.$sopily_instance->_sep.$src);
	$sopily_config=array_merge($sopily_config,$config);
}

?>
